<?php
/**************************************************************************
 ESAM (EVE to SMF API Module)
 Copyright (C) 2009  Clinton Weiss

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **************************************************************************/

if (!defined('SMF')) die('Hacking attempt...');

require_once 'EsamGlobal.php';
require_once 'EsamAlliance.php';
require_once 'EsamQuery.php';
require_once 'EsamValidator.php';

function EsamProfileSettings() {
	global $context, $txt, $scripturl;

	$id_member =  $context['member']['id'];
	$esamQuery = new EsamQuery();
	$esamQuery->setQuery($esamQuery->Q_EVE_API);
	$esamQuery->setParameter("member_id", $id_member);
	$resultSet = $esamQuery->getResultSet();
	$row = count($resultSet) > 0 ? $resultSet[0] : array();

	$user_id = empty($row['USER_ID']) ? "" : $row['USER_ID'];
	$api_key = empty($row['API_KEY']) ? "" : $row['API_KEY'];

	displayApiTable($user_id, $api_key, $id_member);
}

function displayApiTable($user_id = "", $api_key = "", $member_id = null) {
	global $txt;

	$eveApi = new EsamApi();
	if ( !$eveApi->isApiOnline()) {
		echo "API is offline";
		return;
	}

	$esamValidator = new EsamValidator();
	$esamGlobal = new EsamGlobal();

	$validApiKey = (empty($user_id) && empty($api_key)) ? false :  $esamValidator->checkUserAndKey($user_id, $api_key);

	// If this is the registration page, $member_id will be null
	// so no need to display the INVALID message here
	if ($member_id != null) {
		if ( $validApiKey == false) {
			echo "<p style='color: red; font-weight: bold;'>" . $txt['eve_invalid_api'] . "</p>";
		}
	}
	if ( $esamGlobal->getGlobalSetting('GLOBAL_REQUIRED_API', "false") == "true" && $validApiKey == false) {
		echo "<p style='color: red; font-weight: bold;'>" . $txt['eve_valid_api'] . "</p>";
	}

	echo "<b> " . $txt['eve_settings'] . "</b>
		<br /><br />
		<span style='float: left; width: 6em; font-weight: bold;'>User Id:</span>
		<input name='esamUserId' id='esamUserId' type='text' maxlength='8' size='12' value='$user_id'></input>
		<br /><br />
		<span style='float: left; width: 6em; font-weight: bold;'>API Key:</span>
		<input name='esamApiKey' id='esamApiKey' type='text' maxlength='64' size='85' value='$api_key'></input>
		<p>" . $txt['eve_get_api'] . "</p>
      ";


	if (!empty($user_id) && !empty($api_key) && !empty($member_id)) {

		$esamMembers = new EsamMembers();
		$usersPreferredChar = $esamMembers->getMemberSetting($member_id, "PREFERRED_CHAR_ID", "all");

		$eveApi = new EsamApi();
		try {
			$data = $eveApi->getCharacters($user_id, $api_key);
		} catch (Exception $ex) {
			$data = null;
		}

		if (!$eveApi->isApiError()) {
			$checked = ("all" == $usersPreferredChar ? "checked='true'" : "" );
			echo "<fieldset><legend>" . $txt['eve_select_toon'] . "</legend>
							<input type='radio' name='esamMainChar' group='esamMainChar' value='all' $checked> " . $txt['eve_display_all'] . " <br />
      ";

			foreach($data->result->rowset->row as $row) {
				$toonId = $row['characterID'];
				$toonName = $row['name'];

				$corp_id = $row['corporationID'];
				$corp_name = $row['corporationName'];

				$ea = new EsamApi();
				$axml = $ea->getCorporationInfo($corp_id);
				$alliance_id = $axml->result->allianceID;
				$alliance_name = (string) $alliance_id == '0' ? "None" : $axml->result->allianceName;

				$checked = ((string) $toonId == (string) $usersPreferredChar ? "checked='true'" : "" );
				echo "<input type='radio' name='esamMainChar' group='esamMainChar' value='$toonId' $checked> $toonName / $corp_name / $alliance_name <br />";
			}
			echo "</fieldset>";
		}
	}

	echo "		<hr width='100%' size='1' class='hrcolor' />";
}

/**
 * Cleans up the passed string to prevent API injection
 */
function cleanup($string, $maxLength) {
	$string = stripslashes($string);
	$string = preg_replace("/[^A-Za-z0-9]*/", '', $string);
	$string = substr($string, 0, $maxLength);
	return $string;
}

function saveEsamApiChanges($id_member) {
	global $context, $txt;

	if (empty($id_member)) {
		fatal_lang($txt['eve_invalid_api'], false);
	}

	if (isset($_POST['esamMainChar'])) {
		$esamMember = new EsamMembers();
		$selected = cleanup($_POST['esamMainChar'], 64);

		if ($selected == "all") {
			$esamMember->removeMemberSetting($id_member, "PREFERRED_CHAR_ID");
		} else {
			$esamMember->setMemberSetting($id_member, "PREFERRED_CHAR_ID", $selected);
		}
	}

	if (isset($_POST['esamUserId']) && isset($_POST['esamApiKey'])) {
		$api_key = cleanup($_POST['esamApiKey'], 64);
		$user_id = cleanup($_POST['esamUserId'], 8);

		$esamValidator = new EsamValidator();
		if ($esamValidator->checkUserAndKey($user_id, $api_key)) {
			// Save it
			$esamMembers = new EsamMembers();
			$esamMembers->saveEveUserData($id_member, $user_id, $api_key);
			// then give them MemberGroups based on the rules
			$esamValidator->validateApiKeys($id_member);
		}
		else {
			$esamGlobal = new EsamGlobal();
			if ( allowedTo('admin_forum') ) {
				$esamMembers = new EsamMembers();
				if (empty($api_key) && empty($user_id)) {
					$esamMembers->removeEveUserData($id_member);
				}
				else {
					$esamMembers->saveEveUserData($id_member, $user_id, $api_key);
				}
			}
			else if ( $esamGlobal->getGlobalSetting("GLOBAL_REQUIRED_API", "false") == "true") {
				fatal_error($txt['eve_invalid_api_back'], false);
			}
		}
	}
}

function verifyApiKey($user_id, $api_key) {
	global $context, $txt;

	$esamGlobal = new EsamGlobal();
	if ( $esamGlobal->getGlobalSetting("GLOBAL_REQUIRED_API", "false") == "true") {
		$esamValidator = new EsamValidator();
		if (!$esamValidator->checkUserAndKey($user_id, $api_key)) {
			fatal_error($txt['eve_invalid_api_back'], false);
		}}
}

function saveAndValidate($member_id, $user_id, $api_key) {
	$esamMember = new EsamMembers();
	$esamMember->saveEveUserData($member_id, $user_id, $api_key);

	$esamValidator = new EsamValidator();
	$esamValidator->validateApiKeys($member_id);
}
?>
